<template>
  <div class="page-detail screen-design">
    <GoBack/>
    <!-- 左侧组件选择树 -->
    <div class="zone-block left-tree">
      <ScreenElementSideSelector @element-click="addNewElement"/>
    </div>
    <!--    中部画布-->
    <div v-loading="loading" class="mid-content">
      <div class="zone-block design-header">
        <span class="header-text">{{ screen.name }}</span>
        <el-button @click="saveElements" type="primary" :disabled="loading">保存设计</el-button>
        <el-button @click="initLoad">刷新</el-button>
        <el-button text type="success" @click="openFormSettingRef">参数</el-button>
        <el-button
          v-if="screen && screen.facilityId"
          text type="success"
          @click="openFacilitySettingRef">驿站
        </el-button>
      </div>
      <div class="zone-block canvas-wrap">
        <ScreenDesignCanvas
          v-model:active-index="activeIndex"
          :elements="elements"
          :screen="screen"/>
      </div>
    </div>
    <div v-loading="loading" class="zone-block right-content">
      <ScreenDesignStyleForm/>
    </div>
    <!--    右侧元素编辑-->
    <ScreenSettingForm ref="formSettingRef"/>
    <!--  表单弹窗：配置参数-->
    <FacilitySettingForm ref="facilitySettingRef"/>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref} from 'vue'
import {useRoute} from 'vue-router'
import * as ScreenApi from '@/api/yz/screen'
import * as ScreenElementApi from '@/api/yz/screenelement'
import ScreenElementSideSelector from '@/views/yz/screenelement/ScreenElementSideSelector.vue'
import ScreenDesignCanvas from '@/views/yz/screen/ScreenDesignCanvas.vue'
import ScreenSettingForm from "@/views/yz/screen/ScreenSettingForm.vue";
import FacilitySettingForm from "@/views/yz/facility/FacilitySettingForm.vue";
import ScreenDesignStyleForm from '@/views/yz/screen/ScreenDesignStyleForm.vue'
import {provide} from "vue";

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const route = useRoute()

// 设施ID
const screenId = computed(() => {
  return route.query.id as any as number
})
const loading = ref(false)
// 加载时获取屏幕信息
const screen = ref({id: undefined, name: ''})
const loadScreen = async () => {
  screen.value = await ScreenApi.getScreen(screenId.value)
}
// 屏幕元素列表
const elements = ref([
  {
    id: undefined,
    title: undefined,
    style: undefined,
    layer: undefined,
    ruleJsonStr: undefined,
    stateArrayStr: undefined,
    content: undefined,
    screenId: undefined,
    name: undefined,
    type: undefined,
    box: "",
    boxObj: {}
  }
])
const loadScreenElements = async () => {
  const res = await ScreenElementApi.getScreenElementPage({
    pageNo: 1,
    pageSize: 100,
    screenId: screenId.value
  })
  elements.value = res.list.map(item => {
    let boxObj = {}
    if (item.box) {
      try {
        boxObj = JSON.parse(item.box)
      } catch (e) {
        console.log(e)
      }
    }

    return {
      ...item,
      boxObj
    }

  })
  // 按layer排序，后重置序号
  resort()
  resetLayer()
}
// 加载需要的数据
const initLoad = async () => {
  if (!screenId.value) {
    return
  }
  loading.value = true
  try {
    await loadScreen()
    await loadScreenElements()
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
onMounted(async () => {
  await initLoad()
})

// 添加元素到布局图
const addNewElement = (formData) => {
  // 层级等于当前最大层级+1
  const layer = Math.max(...elements.value.map(ele => ele.layer)) + 1
  elements.value.push({
    boxObj: {},
    ...formData,
    screenId: screenId.value,
    layer,
      init: true
  })
  activeIndex.value = elements.value.length - 1
}

// 按序号重新排序
const resort = () => {
  elements.value.sort((a, b) => a.layer - b.layer)
}
// 重置元素层级
const resetLayer = () => {
  elements.value.forEach((ele, i) => {
    ele.layer = i
  })
}
// 保存布局元素
const saveElements = async () => {
  loading.value = true
  try {
    // 保存之前格式数据
    resort()
    resetLayer()
    elements.value.forEach(item => {
      item.box = JSON.stringify(item.boxObj)
    })
    await ScreenElementApi.updateElementByScreenId({
      screenId: screenId.value,
      list: elements.value
    })
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

// 当前激活元素
const activeIndex = ref(0);
const activeElement = computed(() => {
  return elements.value[activeIndex.value] || {type: ''}
})
const changeActiveElement = (value, index) => {
  elements.value.splice( index || activeIndex.value, 1, value)
}
// 移除激活元素
const removeActiveElement = async (index) => {
    debugger
  try {
    // 删除的二次确认
    await message.delConfirm()
    elements.value.splice(index, 1)
    activeIndex.value = 0;
  } catch {}
}


/** 修改参数配置 */
const formSettingRef = ref()
const openFormSettingRef = () => {
  formSettingRef.value.open(screenId.value)
}
/** 修改参数配置 */
const facilitySettingRef = ref()
const openFacilitySettingRef = () => {
  facilitySettingRef.value.open(screen.value.facilityId)
}

// 透传给子组件
provide('screen', screen)
provide('elements', elements)
provide('activeElement', activeElement)
provide('activeIndex', activeIndex)
provide('changeActiveElement', changeActiveElement)
provide('removeActiveElement', removeActiveElement)
</script>
<style scoped lang="scss">
.screen-design {
  position: fixed;
  width: 100vw;
  height: 100vh;
  top: 0;
  left:0;
  padding-top: 40px;
  z-index:1002;
  overflow: auto;
  background: var(--app-content-bg-color);
}
.page-detail {

  display: flex;

  .zone-block {
    border-radius: 10px;
    flex-shrink: 0;
    background: white;
  }

  .left-tree {
    width: 240px;
  }

  .mid-content {
    margin-left: 8px;
    min-width: 375px;
    overflow:auto;
  }

  .design-header {
    padding: 8px;
  }

  .header-text {
    margin-right: 10px;
    font-size: 16px;
    font-weight: bold;
  }

  .canvas-wrap {
    box-sizing: border-box;
    margin-top: 8px;
    padding: 8px;
    width: 100%;
    height: calc(100vh - 100px);
    overflow: auto;
  }

  .right-content {
    margin-left: 8px;
    padding: 8px;
    width: 375px;
    overflow: auto;
    flex-grow: 1;
    flex-shrink: 0;
  }
}
.current-zone {
  margin-bottom:8px;
  padding: 8px;
  border-bottom: 1px solid lightgrey;
}
</style>
